<?php

    class ProductController extends Zend_Controller_Action
    {

        public function init()
        {
            $this->commonModel = $model = new Application_Model_Common();

            $x = new Zend_Auth_Storage_Session('User_Auth');
            $y = $x->read();
            if (!empty($y))
                $this->user_id = $x->read()->rkn_uid;
            $this->user = (array) $y;
        }

        public function indexAction()
        {
            //$session = new Zend_Session;
            $product_id = $this->_getParam('product_id');
            $records = $this->commonModel->getAllRecordFromInnerJoin(array("p" => "rkn_product"), array("b" => "rkn_brand"), "p.brand_id=b.brand_id", "status = '1' and rkn_prod_id = '" . $product_id . "' ", "rkn_prod_id desc");
            
            $this->view->alldata = $records;

            $brand_features = $this->commonModel->getAdapter()->select()->from("rkn_brand")
                    ->join("rkn_product", "rkn_product.brand_id = rkn_brand.brand_id ")
                    ->where("status='1' and brand_status = '1' and rkn_product.brand_id = '" . $records[0]['brand_id'] . "' ")
                    ->order("rkn_brand.brand_id desc")
            ;

            $brand_features = $brand_features->query()->fetchAll();
            $this->view->brandFeatures = $brand_features;


            if ($user_id = @$this->user_id)
                $cartdata = $this->commonModel->getAdapter()->select()->from(array("c" => RKN_CART), array('cart_id', 'user_id', 'product_id', 'brand_id', 'product_quantity', new Zend_Db_Expr('sum(p.price*c.product_quantity) as total_price')))
                                ->join(array("p" => RKN_PRODUCT), "c.product_id=p.rkn_prod_id")
                                ->join(array("b" => RKN_BRAND), "p.brand_id=b.brand_id")
                                ->where("c.user_id = $user_id")
                                ->group('c.cart_id')
                                ->order("c.cart_id DESC")
                                ->query()->fetchAll();

            $this->view->cartdata = (!empty($alldata) && $alldata[0]['cart_id'] ) ? $alldata : '';

            //get review data
            //$reviewData = $this->commonModel->getAllRecordDetail(RKN_REVIEW,"review_product_id = $product_id ");
            $whereCond = "review_product_id = '$product_id' and review_status = '1' ";
            $reviewData = $this->commonModel->getAdapter()->select()->from(RKN_REVIEW, array('review_product_id', 'review_text', 'review_rating', 'review_date', 'review_status', new Zend_Db_Expr('(select sum(review_rating)/count(*) from ' . RKN_REVIEW . ' where ' . $whereCond . ' ) as avg_review')))
                    ->where($whereCond)
                    ->group("review_id")
            ;

            //prd($reviewData->__toString());
            $reviewData = $reviewData->query()->fetchAll();
            //prd($reviewData);
            $this->view->reviewdata = $reviewData;
            //review form post
            if ($this->getRequest()->isPost())
            {
                $arr = $this->getRequest()->getPost();
                //check valid data
                if (!empty($arr['review_text']) && !empty($arr['score']))
                {
                    $dataForm = array();
                    $dataForm['review_rating'] = strip_tags($arr['score']);
                    $dataForm['review_text'] = strip_tags($arr['review_text']);
                    $dataForm['review_product_id'] = $product_id;
                    
                    $this->commonModel->insertRecordData($dataForm, RKN_REVIEW);

                    $this->_helper->FlashMessenger(
                            array('success' => '<strong>Success!</strong> Your review has been submitted for admin approval!')
                    );
                }
                else
                {

                    if (empty($arr['review_text']))
                    {
                        $this->_helper->FlashMessenger(
                                array('error' => '<strong>Oops!</strong> Please fill comment!')
                        );
                    }
                    else
                    {
                        $this->_helper->FlashMessenger(
                                array('error' => '<strong>Oops!</strong> Please mark rating!')
                        );
                    }
                }
                $this->_redirect("product/index/product_id/$product_id");
            }
        }

        public function allAction()
        {
            $commonModel = new Application_Model_Common;
            $where = $whereC = "";
            if ($this->getRequest()->isPost())
            {
                $search_text = $this->getRequest()->getPost('text');

                //$where = " and  find_in_set('$search_text',search_words) ";
                $where = " and  locate('" . strtolower($search_text) . "',lower(search_words)) > 0 ";
                $whereC = " and  locate('" . strtolower($search_text) . "',lower(search_words)) > 0 ";
            }

            //category filter records
            $category = $this->_getParam('c');
            if (!empty($category) && $category != 'all')
            {

                $where .= " and c.cat_id = $category ";
                
            }
            
            //sub child category filter
            $subChildCategory = $this->_getParam("sc");
            if(!empty($subChildCategory)){
                $where .= " and sc.schild_id = $subChildCategory  ";
                $whereC .= " and sc.schild_id = $subChildCategory  ";
            }
            
            //Sub Category Filter
            $subcategory = $this->_getParam('s');
            if(!empty($subcategory)){
                $where .= " and sub.scat_id = $subcategory  ";
                $whereC .= " and sub.scat_id = $subcategory  ";
            }
            //color filter records
            $color = $this->_getParam('color');
            if (!empty($color))
            {
                $color = explode('|', $color);
                $where .= " and ( ";
                $whereC .= " and ( ";
                foreach ($color as $cKey => $cVal)
                {
                    $where .= " find_in_set('" . $cVal . "',color) ";
                    $whereC .= " find_in_set('" . $cVal . "',color) ";
                    if (count($color) != $cKey + 1)
                    {
                        $where .= " or ";
                        $whereC .= " or ";
                    }
                    else
                    {
                        $where .= ") ";
                        $whereC .= ") ";
                    }
                }
            }

            //size filter records
            $size = $this->_getParam('size');
            if (!empty($size))
            {
                $size = explode('|', $size);
                $where .= " and ( ";
                $whereC .= " and ( ";
                foreach ($size as $sKey => $sVal)
                {
                    $where .= " find_in_set('" . $sVal . "',size) ";
                    $whereC .= " find_in_set('" . $sVal . "',size) ";
                    if (count($size) != $sKey + 1)
                    {
                        $where .= " or ";
                        $whereC .= " or ";
                    }
                    else
                    {
                        $where .= ") ";
                        $whereC .= ") ";
                    }
                }
            }
            //price filter records
            $price = $this->_getParam('price');
            if(!empty($price))
            {
                $price = explode('-',$price);
                foreach($price as $pKey=>$pVal)
                {
                    $where .= " and  price >= '".$price[0]."' and price <= '".$price[1]."' ";
                    $whereC .= " and  price >= '".$price[0]."' and price <= '".$price[1]."' ";
                }
            }
            $records = $this->commonModel->getAdapter()->select()->from(array("p" => "rkn_product"))
                    ->join(array("c" => "rkn_category"),"p.cat_id=c.cat_id")
                    ->joinLeft(array("sub"=>"rkn_sub_category"),"sub.scat_id = p.sub_cat_id",array("scat_id","cat_name as sub_cat_name"))
                    ->joinLeft(array("sc"=>"rkn_sub_child_category"),"sc.schild_id = p.schild_id")
                    ->where("p.status = '1' $where ")
                    ->order('rkn_prod_id desc')
                    ;
            $records = $records->query()->fetchAll();
            
            //$records = $this->commonModel->getAllRecordFromInnerJoin(array("p" => "rkn_product"), array("c" => "rkn_category"), "p.cat_id=c.cat_id", "p.status = '1' $where ", "rkn_prod_id desc");
            //$featuredRecords = $this->commonModel->getAllRecordDetail(RKN_PRODUCT, " features='1' ", " rkn_prod_id desc ", "2");
            
            
            $catSubQuery = new Zend_Db_Expr("(
                                              select count(*) as _count from rkn_category as c 
                                              inner join rkn_product p on p.cat_id = c.cat_id
                                              left join rkn_sub_category sub on sub.scat_id = p.sub_cat_id
                                              left join rkn_sub_child_category sc on sc.schild_id = p.schild_id
                                              where c.status = '1' and p.status='1' $whereC
                                              group by c.cat_id
                                              union
                                              select 0 as _count from rkn_category where rkn_category.status = '1' 
                                              group by rkn_category.cat_id
                                            ) as _count ");
            
            $blankCatRecord = $this->commonModel->getAdapter()->select()->from(array("c" => "rkn_category"),array( new Zend_Db_Expr(" 0 as _count"),"c.cat_id"))
                              ->group("c.cat_id")
                    ;
            $catRecords = $this->commonModel->getAdapter()->select()->from(array("c" => "rkn_category"),array("count(*) as _count","c.cat_id"))
                     ->join(array("p" => "rkn_product"), "c.cat_id = p.cat_id ",array())
                     ->joinLeft(array("sub"=>"rkn_sub_category"),"sub.scat_id = p.sub_cat_id",array())
                    ->joinLeft(array("sc"=>"rkn_sub_child_category"),"sc.schild_id = p.schild_id",array())
                    ->where("p.status = '1' $whereC ")
                    ->group("c.cat_id")
                    ;
            

            //$finalCatRecords = $this->commonModel->getAdapter()->select()->from(array("u"=>$this->commonModel->getAdapter()->select()->union(array($catRecords,$blankCatRecord)) ) );
            
            
            $finalCatRecords = $this->commonModel->getAdapter()->select()->from(array("u"=>$this->commonModel->getAdapter()->select()->union(array($catRecords,$blankCatRecord)) ) )
                    ->join("rkn_category","rkn_category.cat_id = u.cat_id")
                    ->join("rkn_sub_category","rkn_sub_category.cat_id = u.cat_id",array(new Zend_Db_Expr("group_concat(distinct scat_id) as subcategories")))
                    ->joinLeft(array("p" => "rkn_product"), "u.cat_id = p.cat_id ", array('status', 'brand_id', 'rkn_prod_id', 'prod_name', 'price', 'full_desc', 'images', 'prod_code', 'in_stock', 'short_desc', 'size'))
                    ->group("u.cat_id");
            
////            $catRecords = $this->commonModel->getAdapter()->select()->from(array("c" => "rkn_category"), array('cat_name', 'cat_id', 'status', $catSubQuery))
//                    ->joinLeft(array("p" => "rkn_product"), "c.cat_id = p.cat_id ", array('status', 'brand_id', 'rkn_prod_id', 'prod_name', 'price', 'full_desc', 'images', 'prod_code', 'in_stock', 'short_desc', 'size'))
//                    ->where(" c.status = '1' ")
//                    ->group("c.cat_id")
//            ;
            //$catRecords = $catRecords->query()->fetchAll();
            $catRecords = $finalCatRecords->query()->fetchAll();
            
            $featuredRecords = array();
            foreach($records as $fKey=>$fVal){
                if($fVal['features'] == '1')
                    $featuredRecords[] = $fVal;
                
                if(count($featuredRecords) >= 2) break;
            }
            
            $this->view->catdata = $catRecords;
            $this->view->alldata = $records;
            $this->view->featureddata = $featuredRecords;
            $this->view->search_text = @$search_text;
            $this->view->params = $this->getRequest()->getParams();
            
            
        }

        public function addtocartAction()
        {
//            prd($this->getAllParams());
            if (!$this->user_id)
            {
                $this->_helper->FlashMessenger(
                        array('error' => '<strong>Oops!</strong> You are not logged in!')
                );
                $this->_redirect("");
            }
            $user_id = $this->user_id;
            $product_id = @$this->_getParam('product_id');
            $brand_id = @$this->_getParam('brand_id');
            $product_quantity = @$this->_getParam('quantity');
            $product_size = @$this->_getParam('size');
            $product_color = @$this->_getParam('color');
            $from_ipaddress = $_SERVER["REMOTE_ADDR"];
            $browser_agent = $_SERVER['USER_AGENT'];

            $data_array = array(
                'user_id' => $user_id,
                'product_id' => $product_id,
                'brand_id' => $brand_id,
                'product_quantity' => $product_quantity,
                'product_size' => $product_size,
                'product_color' => $product_color,
                'from_ipaddress' => $from_ipaddress,
                'browser_agent' => $browser_agent,
            );


            $model = new Application_Model_Common();
            $is_exists = $model->is_exists(RKN_CART, "user_id = $user_id AND product_id = $product_id AND product_color = '$product_color' AND product_size = '$product_size'");
            if (empty($is_exists))
            {
                // no such product already exists in the cart of the user
                $model->insertRecordData($data_array, RKN_CART);
            }
            else
            {
                $model->update($data_array, "user_id = $user_id AND product_id = $product_id AND product_color = '$product_color' AND product_size = '$product_size'");
            }
            $this->_redirect("cart");
        }

        function detailAction()
        {
            $this->_helper->layout()->disableLayout();
            $product_id = $this->_getParam('product_id');
            $productData = $this->commonModel->getAllRecordDetail(RKN_PRODUCT, " rkn_prod_id = $product_id ");
            $this->view->alldata = $productData;

            $whereCond = "review_product_id = '$product_id' and review_status = '1' ";
            $reviewData = $this->commonModel->getAdapter()->select()->from(RKN_REVIEW, array('review_product_id', 'review_text', 'review_rating', 'review_date', 'review_status', new Zend_Db_Expr('(select sum(review_rating)/count(*) from ' . RKN_REVIEW . ' where ' . $whereCond . ' ) as avg_review')))
                    ->where($whereCond)
                    ->group("review_id")
            ;

            //prd($reviewData->__toString());
            $reviewData = $reviewData->query()->fetchAll();
            $this->view->reviewdata = $reviewData;
        }

    }